package diva.pap;

import static diva.lib.lang.Lang.alert;
import static diva.lib.lang.Lang.info;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import diva.android_library.ActivityPresenter;
import diva.android_library.rpc.Response;
import diva.pap.affiliate.AffiliateActivity;
import diva.pap.merchant.MerchantActivity;
import diva.pap.model.Application;

public class LoginPresenter extends ActivityPresenter {

  protected final Application application = Application.getInstance();

  public LoginPresenter(Activity activity) {
    super(activity);
  }

  public void onCreate(Bundle state) {
    info(application.isSetup());
    if (application.isSetup()) {
      setContentView(R.layout.login);
      new LoginRequest(activity, new Response<LoginRequest>() {
        public void onReuestDone(LoginRequest data) {
          if (data.isSuccess())
            onLoginSuccess(data);
          else onLoginFailed();
        }

        public void onReuestFailed() {
          onRequestFailed();
        }
      }).send();
    } else switchActivity(new Intent(activity, SettingsActivity.class));
  }

  protected void onLoginFailed() {
    alert(getString(R.string.login_msg_loginfailed));
    switchActivity(new Intent(activity, SettingsActivity.class));
  }

  private void onLoginSuccess(LoginRequest data) {
    if (data.isMerchant())
      switchActivity(new Intent(activity, MerchantActivity.class));
    else switchActivity(new Intent(activity, AffiliateActivity.class));
  }

  private void onRequestFailed() {
    switchActivity(new Intent(activity, SettingsActivity.class));
  }
}
